import * as PIXI from 'pixi.js'
import Mini3d from './mini3d'
import { Math2 } from './utils/math'

// 群星
export default class Star {
  constructor() {
    this.view = new PIXI.Container()
    this.clouds = []
    this.range = 2e3
    this.speed = -5
    this.count = 0
    this.createStar()
  }

  createStar() {
    let textureCache = PIXI.utils.TextureCache

    // 星空背景
    const spaceBG = PIXI.Sprite.from(textureCache.spaceBG)
    spaceBG.width = window.innerWidth
    spaceBG.height = window.innerHeight
    spaceBG.anchor.set(0.5)
    spaceBG.x = window.innerWidth / 2
    spaceBG.y = window.innerHeight / 2
    spaceBG.scale.set(1.185)
    this.spaceBG = spaceBG
    this.view.addChild(spaceBG)

    // 这个图其实可以不加
    const sun = PIXI.Sprite.from(textureCache.sun)
    sun.anchor.set(0.5)
    sun.x = window.innerWidth / 2
    sun.y = window.innerHeight / 2
    this.view.addChild(sun)

    // 群星
    this.mini3d = new Mini3d()
    this.createStars([textureCache.spaceCloud1, textureCache.spaceCloud2, textureCache.spaceCloud3])
    this.view.addChild(this.mini3d.view)
  }

  createStars(cloudsSC) {
    // 星云对象
    const cloudObject = (texture) => {
      const cloud = PIXI.Sprite.from(texture)
      cloud.anchor.set(0.5)
      cloud.position3d = { x: 0, y: 0, z: 0 }
      cloud.scaleOffset = new PIXI.Point(1, 1)
      return cloud
    }

    // 添加星云背景
    for (let i = 0; 30 > i; i++) {
      const cloud = cloudObject(cloudsSC[i % 3])
      cloud.blendMode = PIXI.BLEND_MODES.SCREEN
      cloud.rotSpeed = 4
      cloud.position3d.z = -(this.range / 30) * i
      this.mini3d.addChild(cloud)
      this.clouds.push(cloud)
      
    }
  }

  update() {
    for (let i = 0; i < this.clouds.length; i++) {
      let cloud = this.clouds[i]
      cloud.position3d.z += this.speed
      cloud.position3d.z < 300 ? (cloud.alpha = cloud.position3d.z / 300) : (cloud.alpha += 0.01 * (1 - cloud.alpha))
      cloud.rotation += cloud.rotSpeed

      if (cloud.position3d.z < 0) {
        cloud.scaleRatio = 5
        cloud.rotSpeed = Math2.random(-5e-4, 5e-4)
        cloud.position3d.z += this.range
        cloud.position3d.x = Math2.random(-4950, 4950)
        cloud.position3d.y = Math2.random(-4950, 4950)
        cloud.alpha = 0
        cloud.rotation = 0
        cloud.scaleOffset.x = Math2.random(1, 1.2)
        cloud.scaleOffset.y = Math2.random(1, 1.2)
        Math.random() < 0.5 && (cloud.scaleOffset.x *= -1)
      }
    }

    this.mini3d.update()
    this.count += 0.25
    this.mini3d.rotation = 0.08 * Math.cos(0.02 * this.count)
    this.mini3d.position3d.y = 200 * Math.sin(0.03 * this.count)
    this.mini3d.position3d.y -= 50
    this.mini3d.rotation3d.y = 0.2 * Math.sin(0.02 * this.count * 0.5)

    this.spaceBG.rotation += 2e-4
  }
}
